package print.folder.name.ui.activity

import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.StrictMode
import android.os.StrictMode.VmPolicy
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.afollestad.materialdialogs.LayoutMode
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.bottomsheets.BottomSheet
import com.afollestad.materialdialogs.files.fileChooser
import com.afollestad.materialdialogs.input.input
import com.blankj.utilcode.constant.PermissionConstants.STORAGE
import com.blankj.utilcode.util.FileIOUtils.readFile2String
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.FileUtils.listFilesInDir
import com.blankj.utilcode.util.PathUtils.getExternalAppDownloadPath
import com.blankj.utilcode.util.PathUtils.getExternalStoragePath
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.item_main.view.*
import print.folder.name.R
import print.folder.name.ui.adapter.Permits
import print.folder.name.ui.adapter.tools
import print.folder.name.ui.adapter.tools.getParentPath
import java.io.File


class MainActivity : AppCompatActivity() {

    //private val initialFolder = "${getExternalDownloadsPath()}/"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Permits.iniQ(this, object : Permits.Callback {
            override fun ok() {
                recINI()
            }
        }, STORAGE)

        iniView()
    }

    private fun recINI() {
        val recycler = recyclerView
        val adapter =
            object :
                BaseQuickAdapter<File, BaseViewHolder>(
                    R.layout.item_main,
                    listFilesInDir(getExternalAppDownloadPath())
                ) {
                override fun convert(holder: BaseViewHolder, item: File) {
                    holder.apply {
                        setText(R.id.textView, item.name)

                    }
                }

            }
        recycler.adapter = adapter
        recycler.layoutManager = LinearLayoutManager(this)
        adapter.setOnItemClickListener { _, view, _ ->
            val id = view.textView.text.toString()
            detectFileUriExposure()
            MaterialDialog(this).show {
                cornerRadius(8f)
                positiveButton(text = "分享") {

                    share(id)
                }
                negativeButton(text = "浏览") {
                    MaterialDialog(this@MainActivity).show {
                        cornerRadius(8f)
                        title(text = "仅显示部分内容")
                        message(text = readFile2String("${getExternalAppDownloadPath()}/${id}"))
                    }
                }
            }
        }
    }

    private fun iniView() {
        floatingActionButton.setOnClickListener {
            MaterialDialog(this, BottomSheet(LayoutMode.WRAP_CONTENT)).show {
                cornerRadius(8f)
                fileChooser(this@MainActivity, File(getExternalStoragePath())) { _, file ->
                    if (getExternalStoragePath() == getParentPath(file.path)) {
                        ToastUtils.showLong("禁止套娃")
                    } else {
                        fileIs(file)
                        //ToastUtils.showLong("${getExternalStoragePath()}\n${file.path}")
                    }
                }
            }
        }
    }

    private fun fileIs(file: File) {
        MaterialDialog(this@MainActivity).show {
            cornerRadius(8f)
            input(hint = "文件名称", maxLength = 8) { _, text ->
                detectFileUriExposure()
                if (FileUtils.isFileExists("${getExternalAppDownloadPath()}/${text}.txt")) {
                    ToastUtils.showLong("已存在！请重新命名")
                    fileIs(file)
                } else {
                    tools.run_Path(
                        File(tools.getParentPath(file.path)),
                        text.toString()
                    )
                    fileExists("${text}/.txt")
                }

                //
            }
        }

    }

    private fun fileExists(str: String) {
        MaterialDialog(this@MainActivity).show {
            cornerRadius(8f)
            title(text = "选择一个呗")
            message(text = " 保存路径:${getExternalAppDownloadPath()}")
            positiveButton(text = "分享") {
                share(str)
            }
            negativeButton(text = "保存") {
                recreate()
            }
        }
    }


    private fun detectFileUriExposure() {
        val builder = VmPolicy.Builder()
        StrictMode.setVmPolicy(builder.build())
        builder.detectFileUriExposure()
    }

    private fun share(str: String) {
        val shareIntent = Intent(Intent.ACTION_SEND)
        shareIntent.putExtra(
            Intent.EXTRA_STREAM,
            Uri.fromFile(File("${getExternalAppDownloadPath()}/${str}"))
        )
        shareIntent.type = "text/plain"
        startActivity(Intent.createChooser(shareIntent, ""))
    }

}